package com.xyebank.ledger.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.*;


public class MD5Util {
	private static final Logger							logger	= LoggerFactory.getLogger(MD5Util.class);


    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * sign 验签
     *
     * @param @return 设定文件
     * @return String DOM对象
     * @Exception 异常对象
     */
    public static String sign(Object pojo, String key) {
        if(pojo == null) return null;
        try {
            ObjectMapper oMapper = new ObjectMapper();
            Map<String, Object> map = oMapper.convertValue(pojo, Map.class);

            if(map.containsKey("sign")) {
                map.remove("sign");
            }
            List<String> keys = new ArrayList<String>(map.keySet());
            Collections.sort(keys);

            List<NameValuePair> signParams = new LinkedList<NameValuePair>();
            for (String k : keys) {
                signParams.add(new BasicNameValuePair(k, String.valueOf(map.get(k))));
            }
            String sign = genPackageSign(signParams, key);
            logger.info("calc sign:{}", sign);
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("处理微信验签失败,详细:{}", e.getMessage());
        }
        return null;
    }



    public static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * genPackageSign微信签名
     *
     * @param @return 设定文件
     * @return String DOM对象
     * @Exception 异常对象
     */
    public static String genPackageSign(List<NameValuePair> params, String key) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            if (null != params.get(i).getValue() && !"".equals(params.get(i).getValue())) {
                sb.append(params.get(i).getName());
                sb.append('=');
                sb.append(params.get(i).getValue());
                sb.append('&');
            }
        }
        sb.append("key=");
        sb.append(key);
        logger.info("生成的签名串:{}", sb.toString());
        String packageSign = null;
        try {
            packageSign = MD5Util.MD5(sb.toString()).toUpperCase();
            logger.info("calc sign is:{}", packageSign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packageSign;
    }



    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }



    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }


    public static void main(String[] args) {
        String x = "appid=wx75dc6feb054c4a79&attach=成都总公司&bank_type=CMB_DEBIT&cash_fee=1&device_info=WEB&fee_type=CNY&is_subscribe=N&mch_id=1459986002&nonce_str=04aoFqBsL7h2m5ZIYNluytzc8rgCxvjP&openid=oVuf50F3DWEfPSSJ2p4_3w6oZkH4&out_trade_no=Ymrs1503627203&result_code=SUCCESS&return_code=SUCCESS&time_end=20170825101343&total_fee=1&trade_type=JSAPI&transaction_id=4002712001201708258121228791&key=Wenshikai19910828Wenshikai199108";
        System.out.println(getMessageDigest(x.toString().getBytes()));

        x = "appid=wx75dc6feb054c4a79&attach=成都总公司&bank_type=CMB_DEBIT&cash_fee=1&device_info=WEB&fee_type=CNY&is_subscribe=N&mch_id=1459986002&nonce_str=O31hHEFaGZM87wC2jQluRrITgL4YednP&openid=oVuf50F3DWEfPSSJ2p4_3w6oZkH4&out_trade_no=Ymrs1503626519&result_code=SUCCESS&return_code=SUCCESS&time_end=20170825100216&total_fee=1&trade_type=JSAPI&transaction_id=4002712001201708258120722774&key=Wenshikai19910828Wenshikai199108";
        System.out.println(getMessageDigest(x.toString().getBytes()));
    }
}
